<?php

namespace App\Models;

use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;

class Auth extends Model
{
    use HasFactory;

    /**
     * @return mixed
     *
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getAccessToken()
    {
        $redis = Redis::connection();

        if ($redis->exists('access_token:toutiao')){
            return $redis->get('access_token:toutiao');
        }else{
            $client = new Client();

            $request = $client->post('https://developer.toutiao.com/api/apps/v2/token',[
                'headers' => ['content-type' => 'application/json'],
                'json'=>[
                    'appid'  => env('MP_TOUTIAO_APP_ID'),
                    'secret' => env('MP_TOUTIAO_APP_SECRET'),
                    'grant_type' => 'client_credential',
                ]
            ]);

            $response = json_decode($request->getBody()->getContents(),true);

            if ($response['err_no'] == 0){
                $redis->setex('access_token:toutiao', 7000, $response['data']['access_token']);
                return $response;
            }else{
                return $response['err_tips'];
            }
        }
    }
}
